package com.shawn.rabbitmq.simplemode;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Consumer
 * @Description TODO
 * @Author shawn
 * @date 2021/9/19 4:39 下午
 * @Version 1.0
 */
public class Consumer {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.64.12");
        factory.setUsername("shawn");
        factory.setPassword("shawn");
        System.out.println("消费者等待接收消息");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明队列,如果该队列已经创建过,则不会重复创建
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //收到消息后用来处理消息的回调对象
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String msg = new String(delivery.getBody(), "UTF-8");
            System.out.println("消费者接收到消息： " + msg);
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
    }
}
